/**
 * dom节点
 * initData初始数据
 * x轴数据
 * option配置
 * newOption覆盖原有配置
 */
// import echarts from "echarts";
import { init } from "./lib";
// import { lineOption } from "./options";
// 引入提示框组件、标题组件、工具箱组件。
import "echarts/src/component/tooltip";
import "echarts/src/component/title";
import "echarts/src/component/legendScroll";

import { deepClone } from "./utils";

export default class Base {
    constructor(dom, initData = [], xAxisData = [], option, newOption) {
        this.lineLabel = {
            normal: {
                show: true
            }
        };
        this.xAxisData = xAxisData;
        this.newOption = newOption;
        this.lineColor = "white";
        this.$option = deepClone(option); // 最初的配置
        this.$echart = init(dom); // 初始化
        this.initxAxisData(); // ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
        this.initData(initData);
        this.render();
    }
    initxAxisData() {
        // console.log(this.xAxisData,'this.xAxisData')
        if (this.xAxisData && this.xAxisData.length > 0) {
            this.$option.xAxis.data = deepClone(this.xAxisData);
        }
    }
    setDataLength(xAxisData, data) {
        // 坐标 和 坐标数据长度相等
        while (xAxisData.length > data.length) {
            data.push(0);
        }
    }
    initData(data) {
        if (!(data instanceof Array)) throw new Error("Echart Line 初始化数据请传入 数组");
        let setDataLength = this.setDataLength;
        let xAxisData = this.xAxisData;
        data.forEach(data => {
            let mydata = deepClone(data);
            mydata.label = this.lineLabel;
            setDataLength(xAxisData, mydata.data);
            this.$option.series.push(mydata);
        });
    }
    render() {
        console.log(this.$option, "this.$option");
        this.$option = { ...this.$option, ...this.newOption };
        this.$echart.clear();
        this.$echart.setOption(this.$option);
    }
    setData(datas) {
        let setDataLength = this.setDataLength;
        let xAxisData = this.xAxisData;
        if (!(datas instanceof Array)) {
            this.$option.series.find(serie => {
                if (datas.name === serie.name) {
                    let newdata = deepClone(datas.data);
                    setDataLength(xAxisData, newdata);
                    serie.data = newdata;
                    return true;
                }
            });
        } else {
            this.$option.series.forEach(serie => {
                for (let data in datas) {
                    if (datas[data].name === serie.name) {
                        let newdata = deepClone(datas[data].data);
                        setDataLength(xAxisData, newdata);
                        serie.data = newdata;
                        break;
                    }
                }
            });
        }
        this.render();
    }
}
